package com.kkd.kkdapp.db.app;

import com.kkd.kkdapp.db.app.model.KkdAppInfo;
import com.kkd.kkdapp.db.app.model.KkdExceptionDb;
import com.kkd.kkdapp.db.app.model.Notice;
import com.kkd.kkdapp.db.app.model.PdfUrlModel;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.db.base.BaseEASQLiteOpenHelper;
import com.kkd.kkdapp.db.base.DataObservable;
import com.kkd.kkdapp.db.base.SqlBuilder;
import com.kkd.kkdapp.utils.LogUtil;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

/**
 * 此类应该在具体APP代码中
 * 
 * @author askzhao
 * 
 */
public class EADBHelper extends BaseEASQLiteOpenHelper {
	/** 数据库名称 */
	private static final String DB_NAME = "kkd_db.db";

	/** 数据库版本 */
	private static final int DB_VERSION = 8;

	private static EADBHelper instance;
	public DataObservable onDBCreatedObservable = new DataObservable();

	/** 调用之前必须保证已经调用过init方法 */
	public static synchronized EADBHelper getInstance() {
		return instance;
	}

	public static synchronized void init(Context context) {
		if (null == instance) {
			instance = new EADBHelper(context, DB_NAME, null, DB_VERSION);
		}
	}

	private EADBHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(final SQLiteDatabase db) {
		super.onCreate(db);
		createAllTables(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		super.onUpgrade(db, oldVersion, newVersion);
		LogUtil.d("EADBHelper", "onUpgrade " + oldVersion + ", " + newVersion);
		if (oldVersion < 8) {
			dropAllTables(db);
			createAllTables(db);
		}

	}

	private void createAllTables(final SQLiteDatabase db) {
		db.execSQL(SqlBuilder.getCreateTableSql(User.class));
		db.execSQL(SqlBuilder.getCreateTableSql(KkdExceptionDb.class));
		db.execSQL(SqlBuilder.getCreateTableSql(KkdAppInfo.class));
		db.execSQL(SqlBuilder.getCreateTableSql(Notice.class));
		db.execSQL(SqlBuilder.getCreateTableSql(PdfUrlModel.class));		
	}

	private void dropAllTables(final SQLiteDatabase db) {
		db.execSQL(SqlBuilder.getDropTableSql(User.class));
		db.execSQL(SqlBuilder.getCreateTableSql(KkdExceptionDb.class));
		db.execSQL(SqlBuilder.getCreateTableSql(KkdAppInfo.class));
		db.execSQL(SqlBuilder.getCreateTableSql(Notice.class));
		db.execSQL(SqlBuilder.getCreateTableSql(PdfUrlModel.class));
	}

}
